﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Threading;
using System.Windows.Forms;

using DataReceiver.DataAPI;
using Core.Common;

namespace BgTickMoving
{
    class Program
    {
        static void Main(string[] args)
        {
            //监听关机事件
            SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
            DateTime beginTime = DateTime.Now;


            try
            {
                //尝试3次从mongo获取tick
                List<Bson_Tick> bsonTicks = null;
                for (int i = 0; i < 3;i++ )
                {
                    bsonTicks = MongoOperater.FindTicks(1000);
                    if(bsonTicks.Count > 0)
                    {
                        break;
                    }
                }

                while (bsonTicks.Count > 0 && ShutDownState == 0)
                {
                    //插入成功，然后删除
                    var ticks = bsonTicks.ToList<Model_Tick>();
                    if(SqlOperater.InsertTicks(ticks))
                    {
                        MongoOperater.RemoveTicks(bsonTicks);
                    }

                    //尝试3次从mongo获取tick
                    for (int i = 0; i < 3; i++)
                    {
                        bsonTicks = MongoOperater.FindTicks(1000);
                        if (bsonTicks.Count > 0)
                        {
                            break;
                        }
                    }
                    
                    //发现关机信号，此时可以关机
                    Interlocked.CompareExchange(ref ShutDownState, 2, 1);
                }
            }
            catch(Exception e)
            {
                LogTextHelper.WriteLine("全局异常：" + e.Message);
            }

            //记录导入时间
            var costTime = DateTime.Now - beginTime;
            LogTextHelper.WriteLine("本次导入耗时：" + costTime.TotalMinutes + "分");
        }



        //下面是系统注销或关闭事件处理程序， 
        static volatile int ShutDownState = 0;//0正常，1关机中等待主线程退出，2关机
        private static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
        {
            //发现关机信号，给主线程提示
            Interlocked.CompareExchange(ref ShutDownState, 1, 0);
            MessageBox.Show("正在下载tick");
            while (ShutDownState == 1)
            {
                Thread.Sleep(1000);
            }
        } 
    }
}
